package com.itheima.framework;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;

public class JdbcTemplate {
    private DataSource dataSource;
    public JdbcTemplate(DataSource dataSource){
        this.dataSource = dataSource;
    }
    public int update(String sql,Object...params)throws Exception{
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        int parameterCount = preparedStatement.getParameterMetaData().getParameterCount();
        if (parameterCount!= params.length){
            throw new RuntimeException("期望的参数个是"+parameterCount+",实际是"+params.length);
        }
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i+1,params[i]);
        }
        int count = preparedStatement.executeUpdate();

        preparedStatement.close();
        connection.close();

        return count;
    }
}
